package com.changgou.file.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.file.util.FastDFSClient;
import com.changgou.file.util.FastDFSFile;
import io.netty.util.internal.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;

@RestController
@RequestMapping("/file")
public class FileController {

    @PostMapping("/upload")
    public Result Upload(MultipartFile multipartFile){
        try {
        //判断文件是否存在
        if (multipartFile == null){
            return new Result(false, StatusCode.ERROR,"文件不存在");
        }
        //获取文件完整路径
        String originalFilename = multipartFile.getOriginalFilename();
        if (StringUtils.isEmpty(originalFilename)){
            return new Result(false, StatusCode.ERROR,"文件不存在");
        }
        //获取文件后缀名
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        //获取文件的内容
        byte[] bytes = multipartFile.getBytes();
        //封装实体
        FastDFSFile fastDFSFile = new FastDFSFile(originalFilename, bytes, substring);
         //发送文件,并返回参数
            String[] upload = FastDFSClient.upload(fastDFSFile);
            System.out.println(Arrays.toString(upload));
            //封装结果
            String url = FastDFSClient.getTrackerUrl()+upload[0]+"/"+upload[1];
            return new Result(true,StatusCode.ACCESSERROR,"上传成功",url);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR,"上传文件失败");
        }
    }
}
